package servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import util.TimestampUtil;
import util.enviaEmail;
import bean.empresaBean;
import conexao.Conexao;
import dao.empresaDao;

public class relatorio extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private HashMap<String, Object> parametros = new HashMap<String, Object>();

	public relatorio() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		new File(getServletConfig().getServletContext().getRealPath("/relatorios/relatorio.pdf")).delete();

		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		
		PrintWriter out = response.getWriter();
		
		Connection conn = null;
		try {
			conn = new Conexao().getConexao();
		} catch (SQLException e) {
			new enviaEmail().enviar(e);
			out.print("falhaConexao");
			return;
		}

		String tipoRelatorio = request.getParameter("tipoRelatorio");

		try {
			if (tipoRelatorio.equals("relatorioPorSecretario")) {
				
				String situacao = request.getParameter("situacao");

				Timestamp dataInicial = new TimestampUtil()
						.parseTimestampHoraInicial(request
								.getParameter("dataInicial"));

				Timestamp dataFinal = new TimestampUtil()
						.parseTimestampHoraFinal(request
								.getParameter("dataFinal"));

				Integer id = Integer.parseInt(request.getParameter("id"));
				
				String relatorio = "relatorios/" + tipoRelatorio + ".jasper";
				
				if(situacao != null){
					relatorio = "relatorios/" + tipoRelatorio + "Finalizado.jasper";
				}

				parametros.put("dataInicial", dataInicial);
				parametros.put("dataFinal", dataFinal);
				parametros.put("idSecretario", id);

				imprime(parametros, relatorio, response, request);
				
			}
			if (tipoRelatorio.equals("relatorioPorDesigner")) {
				
				String situacao = request.getParameter("situacao");

				Timestamp dataInicial = new TimestampUtil()
						.parseTimestampHoraInicial(request
								.getParameter("dataInicial"));

				Timestamp dataFinal = new TimestampUtil()
						.parseTimestampHoraFinal(request
								.getParameter("dataFinal"));

				Integer id = Integer.parseInt(request.getParameter("id"));

				String relatorio = "relatorios/" + tipoRelatorio + ".jasper";
				
				if(situacao != null){
					relatorio = "relatorios/" + tipoRelatorio + "Finalizado.jasper";
				}				
				
				parametros.put("dataInicial", dataInicial);
				parametros.put("dataFinal", dataFinal);
				parametros.put("idDesigner", id);

				imprime(parametros, relatorio, response, request);
				
			}
			if (tipoRelatorio.equals("relatorioPorCliente")) {
				
				String situacao = request.getParameter("situacao");

				Timestamp dataInicial = new TimestampUtil()
						.parseTimestampHoraInicial(request
								.getParameter("dataInicial"));

				Timestamp dataFinal = new TimestampUtil()
						.parseTimestampHoraFinal(request
								.getParameter("dataFinal"));

				Integer id = Integer.parseInt(request.getParameter("id"));

				String relatorio = "relatorios/" + tipoRelatorio + ".jasper";
				
				if(situacao != null){
					relatorio = "relatorios/" + tipoRelatorio + "Finalizado.jasper";
				}	
				
				parametros.put("dataInicial", dataInicial);
				parametros.put("dataFinal", dataFinal);
				parametros.put("idCliente", id);

				imprime(parametros, relatorio, response, request);
				
			}
			if (tipoRelatorio.equals("relatorioComissao")) {
				
				Timestamp dataInicial = new TimestampUtil()
						.parseTimestampHoraInicial(request
								.getParameter("dataInicial"));

				Timestamp dataFinal = new TimestampUtil()
						.parseTimestampHoraFinal(request
								.getParameter("dataFinal"));

				Integer id = Integer.parseInt(request.getParameter("id"));

				String relatorio = "relatorios/" + tipoRelatorio + ".jasper";			
				
				parametros.put("dataInicial", dataInicial);
				parametros.put("dataFinal", dataFinal);
				parametros.put("idDesigner", id);

				imprime(parametros, relatorio, response, request);
				
			}
			if (tipoRelatorio.equals("osFinalizado")) {
				
				Timestamp dataInicial = new TimestampUtil()
						.parseTimestampHoraInicial(request
								.getParameter("dataInicial"));

				Timestamp dataFinal = new TimestampUtil()
						.parseTimestampHoraFinal(request
								.getParameter("dataFinal"));
				
				Integer idEmpresa = (Integer) request.getSession().getAttribute("idempresa");
					
				String relatorio = "relatorios/" + tipoRelatorio + ".jasper";			
				
				parametros.put("dataInicial", dataInicial);
				parametros.put("dataFinal", dataFinal);
				parametros.put("idEmpresa", idEmpresa);
				imprime(parametros, relatorio, response, request);
			}
			if (tipoRelatorio.equals("osAberto")) {
				
				Timestamp dataInicial = new TimestampUtil()
						.parseTimestampHoraInicial(request
								.getParameter("dataInicial"));

				Timestamp dataFinal = new TimestampUtil()
						.parseTimestampHoraFinal(request
								.getParameter("dataFinal"));
				
				Integer idEmpresa = (Integer) request.getSession().getAttribute("idempresa");

				String relatorio = "relatorios/" + tipoRelatorio + ".jasper";			
				
				parametros.put("dataInicial", dataInicial);
				parametros.put("dataFinal", dataFinal);
				parametros.put("idEmpresa", idEmpresa);
				imprime(parametros, relatorio, response, request);
			}
			
		} catch (ParseException e) {
			new enviaEmail().enviar(e);
			out.println("Data inválida.");
			return;
		}
		
		if (tipoRelatorio.equals("imprimirOS")) {

			Integer idOs = Integer.parseInt(request.getParameter("id"));
			
			Integer idEmpresa = (Integer) request.getSession().getAttribute("idempresa");
			
			String relatorio = "relatorios/" + tipoRelatorio + ".jasper";

			String logo = "";
			
			empresaBean empresa = null;
			try {
				empresa = new empresaDao().getEmpresa(conn, idEmpresa);
			} catch (SQLException e) {
				new enviaEmail().enviar(e);
				e.printStackTrace();
			}
			
			Integer ID = idEmpresa;
			String base = getServletConfig().getServletContext().getRealPath("/");
			base += "logo/";
			String fileName = base + ID + ".jpg";
			File file = new File(fileName);

			if (file.exists()) {
				logo = getServletConfig().getServletContext().getRealPath("/logo/"+ ID +".jpg"); 
			}else if (empresa.getLogo() != null) {

				FileOutputStream fos = new FileOutputStream(file);
				for (int i = 0; i < empresa.getLogo().length; i++) {
	
					fos.write(empresa.getLogo()[i]);
				}
	
				fos.close();
				fos.flush();
	
				logo = getServletConfig().getServletContext().getRealPath("/logo/"+ ID +".jpg"); 
			}else{
				logo = getServletConfig().getServletContext().getRealPath("/logo/logo.jpg"); 
			}
			
			parametros.put("id", idOs);
			parametros.put("logo", logo);
			imprime(parametros, relatorio, response, request);
		}
		
		if (tipoRelatorio.equals("visualizar")) {

			Integer id = (Integer) request.getSession().getAttribute("idempresa");
			
			String relatorio = "relatorios/" + tipoRelatorio + ".jasper";
			
			String logo = "";
						
			empresaBean empresa = null;
			try {
				empresa = new empresaDao().getEmpresa(conn, id);
			} catch (SQLException e) {
				new enviaEmail().enviar(e);
				e.printStackTrace();
			}
			
			Integer ID = id;
			String base = getServletConfig().getServletContext().getRealPath("/");
			base += "logo/";
			String fileName = base + ID + ".jpg";
			File file = new File(fileName);

			if (file.exists()) {
				logo = getServletConfig().getServletContext().getRealPath("/logo/"+ ID +".jpg"); 
			}else if (empresa.getLogo() != null) {

				FileOutputStream fos = new FileOutputStream(file);
				for (int i = 0; i < empresa.getLogo().length; i++) {
	
					fos.write(empresa.getLogo()[i]);
				}
	
				fos.close();
				fos.flush();
	
				logo = getServletConfig().getServletContext().getRealPath("/logo/"+ ID +".jpg"); 
			}else{
				logo = getServletConfig().getServletContext().getRealPath("/logo/logo.jpg"); 
			}
						
			parametros.put("id", id);
			parametros.put("logo", logo);
			imprime(parametros, relatorio, response, request);
		}

	}

	public void imprime(HashMap<String, Object> parametros, String relatorio, HttpServletResponse response, HttpServletRequest request) throws IOException {

		PrintWriter out = response.getWriter();
		
		Connection conn = null;
		try {
			conn = new Conexao().getConexao();
		} catch (SQLException e) {
			new enviaEmail().enviar(e);
			out.print("falhaConexao");
			return;
		}
		
		try {

			InputStream reportFile = new FileInputStream(getServletConfig()
					.getServletContext().getRealPath(relatorio));
			JasperPrint bytes = null;

			bytes = JasperFillManager.fillReport(reportFile, parametros, conn);
			
			if(!bytes.getPages().isEmpty()){
				
			 JasperExportManager.exportReportToPdfFile(bytes,
			 getServletConfig().getServletContext().getRealPath("/relatorios/relatorio.pdf"));
			 
			 reportFile.close();
			}else{
				out.println("Sem relatório com esses dados.");
			}

			// response.sendRedirect(getServletConfig().getServletContext().getRealPath("/relatorios/relatorio.pdf"));

//			 RequestDispatcher rd = request.getRequestDispatcher("/relatorios/relatorio.pdf");
//			 rd.forward(request, response);

//			JasperViewer jv = new JasperViewer(bytes, false);
//			jv.setTitle("Relatório");
//			jv.setIconImage(Toolkit.getDefaultToolkit().getImage(
//					getServletContext().getRealPath("/imagens/blue-document-text.png")));
//			jv.setVisible(true);

			// JasperViewer.viewReport(bytes, false);

//			 ServletResponse response;
//			 response.setContentType("application/pdf");
//			 response.setContentLength(bytes.length);
//			 ServletOutputStream servletOutputStream = response.getOutputStream();
//			 servletOutputStream.write(bytes, 0, bytes.length);
//			 servletOutputStream.flush();
//			 servletOutputStream.close();

			

		} catch (Exception e) {
			try {
				conn.rollback();
			} catch (Exception ex) {
				new enviaEmail().enviar(ex);
				ex.printStackTrace();
			}
			new enviaEmail().enviar(e);
			throw new RuntimeException(e);
		} finally {
			try {
				conn.close();
			} catch (Exception ex) {
				new enviaEmail().enviar(ex);
			}
		}
	}

}
